﻿using Dapper;
using MediatR;
using MySqlConnector;
using System.Text;
using Warehouse.Api.Read.AllCation.Command;
using Warehouse.Api.Read.Dtos;
using Warehouse.Domian.Model;
using Warehouse.ErrorCode;
using Warehouse.Infrastructrue.Implenment;

namespace Warehouse.Api.Read.AllCation.Hanlder
{
    public class GetStockingCommandHanlder : IRequestHandler<GetStockingCommand, ApiPaging<StockingDtos>>
    {

        public readonly IBaseRepostity<Stocking> _baseRepostity;
        public readonly ILogger<GetStockingCommandHanlder> logger;

        public GetStockingCommandHanlder(IBaseRepostity<Stocking> baseRepostity, ILogger<GetStockingCommandHanlder> logger)
        {
            _baseRepostity = baseRepostity;
            this.logger = logger;
        }
        /// <summary>
        /// 获取获取出入库信息
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>

        public async Task<ApiPaging<StockingDtos>> Handle(GetStockingCommand request, CancellationToken cancellationToken)
        {
            ApiPaging<StockingDtos> result = new ApiPaging<StockingDtos>();
            try
            {
                // 原有Dapper代码已注释，以下为SqlSugar三表联查示例
                
                var countsql = new StringBuilder();
                var sqlbuilder = new StringBuilder();

                sqlbuilder.Append(@"select  stok.id,
                          stok.stid,
                          stok.associatedordernumber,
                          stok.supplierid,
                          stok.orderid,
                         stok. suppliername,
                         stok. supplierphone,
                         stok. productid,
                         stok. bacth,
                         stok.suppliercontacts,
                         stok.price,
                          stok.incomingquantity,
                         stok. totalprice,
                         stok.suppliercontacts,
                          stok.preparedname,
                          stok.suppliercontacts,
                         stok. preparedtime,
                          stok.remark,
                          pro.productname,
                         stok.statename,
                         sup.suppliername,
                         pro.manufacturercode,
                         sup.suppliercode,
                         dep.depotname
                        from stocking stok
                        join productmodel pro
                        on  stok.productid = pro.productid
                        join suppliermodel sup
                        on stok.supplierid = sup.supplierid
                        join depotmodel dep 
                        on stok.storageid = dep.depotid
                        where isdeleted =  false
                         ");
                countsql.Append(@"select count(stok.id) 
                         from stocking stok
                        join productmodel pro
                        on  stok.productid = pro.productid
                        join suppliermodel sup
                        on stok.supplierid = sup.supplierid
                        join depotmodel dep 
                        on stok.storageid = dep.depotid
                        where 0=0 ");
 
                var parmenters = new DynamicParameters();
                //查询订单单号名称
                if (!string.IsNullOrWhiteSpace(request.AssociatedOrderNumber))
                {
                    sqlbuilder.Append("and AssociatedOrderNumber =@AssociatedOrderNumber ");
                    parmenters.Add("AssociatedOrderNumber", request.AssociatedOrderNumber);
                    countsql.Append("and AssociatedOrderNumber = @AssociatedOrderNumber ");
                }

                //查询状态
                if (request.State != null)
                {
                    sqlbuilder.Append("and state = @state ");
                    parmenters.Add("state", request.State);
                    countsql.Append("and state = @state ");
                }
                sqlbuilder.Append("limit @pagesize offset @offset");
                parmenters.Add("pagesize", request.PageSize);
                parmenters.Add("offset", (request.PageIndex - 1) * request.PageSize);
                using var conn = new MySqlConnection("server=10.223.8.23;uid=root;pwd=123456;database=warehousemanagement");
                await conn.OpenAsync(cancellationToken);
                var data = await conn.QueryAsync<StockingDtos>(sqlbuilder.ToString(), parmenters);
                var total = await conn.ExecuteScalarAsync<int>(countsql.ToString(), parmenters);
                if (request.PageSize <= 0)
                {
                    result.Msg = "显示数量不能小于等于0";
                    result.Code = ApiEume.Error;
                    return result;
                }
                result.Msg = "显示成功";
                result.Code = ApiEume.Success;
                result.PageData = data.ToList();
                result.TotaCount = total;
                result.PageCount = (int)Math.Ceiling((double)total / request.PageSize);
                

                // SqlSugar三表联查示例
                // 假设有SqlSugarClient db，且实体为Stocking、Supplier、Product

                // 你可以根据需要进行分页、总数统计等
                // result.PageData = resultList;
                // result.TotaCount = ...;
                // result.PageCount = ...;
            }

            catch (Exception ex)
            { 

                logger.LogError(ex, "获取出入库信息异常");
            }
            return result;

        }
    }
}
